<template>
	<view class="logoBox">
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		openAuth
	} from 'dingtalk-design-libs/biz/openAuth'
	import {
		loginPC,
		getMyInfo,
		setOpenId,
		loginWX,
		loginDing
	} from '@/utils/req/api.js'
	import {
		isWechat,
		isDing,
		companyParams
	} from '@/utils/commen'
	console.log('[ty_Log-------[isDing]] :  -23', isDing())
	console.log('[ty_Log-------[isWechat]] :  -22', isWechat())
	export default {
		data() {
			return {
				code: '',
				froms: '',
				corpId: '',
				clientId: '',
				companyId: '',

				flag: false,
			}
		},
		onLoad(options) {
			console.log('[ty_Log-------[options]] :  -36', options)
			let {
				code,
				froms,
				corpId,
				clientId,
				id: companyId
			} = options
			this.code = code
			this.froms = froms
			this.corpId = corpId
			this.clientId = clientId
			this.companyId = companyId
		},
		onShow() {
			if (uni.getStorageSync('hasNotOverCompanyOrder')) {
				if (window.location.href.split('code').length != 1) {
					console.log('-------------------', window.location.href.split('code')[1].split('&')[0].split('=')[1])
					this.setOpenId(window.location.href.split('code')[1].split('&')[0].split('=')[1])
					uni.redirectTo({
						url: '/pages/order'
					})
				}
				return;
			}
			companyParams({
				companyId: this.companyId,
				clientId: this.clientId,
				corpId: this.corpId,
			})
			if (!this.corpId) uni.removeStorageSync('corpId')

			const isDingCompanyUrl = this.clientId && this.corpId // 钉钉企业单链接携带此参数
			if (uni.getStorageSync('token') && !isDingCompanyUrl) {
				this.toHome()
				return
			}

			if (this.froms) {
				uni.setStorageSync('froms', 'company')
			}

			// 登录后返回单店模式
			if (uni.getStorageSync('orderType') == 'singleMode') {
				// orderType在app.vue里可能随时会销毁，indexPage只在index.vue里销毁
				uni.setStorageSync('indexAfterLogin', 'singleMode')
			}

			if (window.location.href.split('code').length != 1) {
				this.toLogin(window.location.href.split('code')[1].split('&')[0].split('=')[1])
			} else {
				if (isWechat()) {
					// 微信环境则授权登陆微信
					window.location.href =
						'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx50c118fbe2e4490f&response_type=code&scope=snsapi_base&state=abcdefghigklmnopqrstuvwxyz&redirect_uri=https://www.yongshantuan.cn/#wechat_redirect'
				} else {
					if (isDingCompanyUrl) {
						this.dingLogin()
					} else {
						this.pcLogin()
					}
				}
			}
		},
		methods: {
			async toLogin(code) {
				let res = await loginWX({
					code,
				})
				if (res.data.success) {
					uni.removeStorageSync('hasCompanyLogin');
					uni.setStorageSync('token', res.data.result.token)
					let myInfoResult = await getMyInfo()
					uni.setStorageSync('myInfo', myInfoResult.data.result)
					this.$showToast.call(this, '登录成功')
					this.toHome()
				} else {
					this.$showToast.call(this, res.data.message, 'warning')
				}
			},
			//钉钉登录
			async dingLogin() {
				if (this.flag) {
					return
				}
				this.flag = true

				let loginRes = {}
				// 钉钉授权
				const {
					status,
					result = {}
				} = await openAuth({
					clientId: this.clientId,
					corpId: this.corpId, // 当前组织的corpId
					rpcScope: 'Contact.User.Read',
					// fieldScope: 'Contact.User.mobile',
					type: 0, // 0 标识授权个人信息；1 标识授权组织信息
				})
				if (status === 'ok') {
					loginRes = await loginDing({
						authCode: result.authCode,
						companyId: this.companyId,
					})
					this.flag = false
					const {
						success,
						result: loginResult
					} = loginRes.data
					if (success) {
						uni.removeStorageSync('hasCompanyLogin');
						uni.setStorageSync('token', loginResult.token)
						uni.setStorageSync('myInfo', loginResult)
					}
					// setTimeout(() => this.$router.push(`/pages/order?id=${this.companyId}`), 200) // 企业单
					setTimeout(() => {
						uni.redirectTo({
							url: `/pages/order?id=${this.companyId}`,
						})
					}, 200) // 企业单
				}
			},
			//PC登录
			async pcLogin() {
				let loginRes = {}
				// 若缓存无手机号则游客模式登录
				const {
					phoneTakingMeals = ''
				} = uni.getStorageSync('YST_OrderUser') || {}
				const params = phoneTakingMeals ? {
					phone: phoneTakingMeals,
				} : {}
				loginRes = await loginPC(params)
				setTimeout(() => this.toHome(), 200) // 个人单

				const {
					success,
					result: loginResult
				} = loginRes.data
				if (success) {
					uni.removeStorageSync('hasCompanyLogin');
					uni.setStorageSync('token', loginResult.token)
					uni.setStorageSync('myInfo', loginResult)
				}
			},
			toHome() {
				this.$router.push(`/pages/home/index`)
			},
			async setOpenId(code) {
				let res = await setOpenId({
					code,
				})
				console.log('设置openid的res', res)
				uni.redirectTo({
					url: '/pages/order?id=' + uni.getStorageSync('companyId'),
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	.logoBox {
		@include flexs(center, center);
		flex-direction: column;
		min-height: 100vh;
		padding: 0 40rpx;

		.logo {
			width: 150rpx;
			height: 150rpx;
			margin-bottom: 50rpx;
		}

		.telBox,
		.codeBox {
			width: 100%;
			margin: 20rpx 0;
			background-color: #ececec;
			border-radius: 100rpx;
			padding: 5rpx 0;
		}

		.codeBox {
			position: relative;

			.getCode {
				position: absolute;
				right: 0;
				top: 0;
				font-size: 28rpx;
				line-height: 28rpx;
				min-width: 30%;
				max-width: 50%;
				height: 100%;
				@include flexs(center, center);
				color: #fa690a;
				padding-right: 20rpx;
			}

			.dis {
				color: rgba(0, 0, 0, 0.35);
			}
		}

		.commenButton {
			padding: 20rpx 0;
			background-color: #fa690a;
			margin-top: 40rpx;
		}
	}
</style>
<style lang="scss">
	.telBox,
	.codeBox {
		.u-input {
			border: 1px solid red;
			border-color: rgba(0, 0, 0, 0) !important;
			text-indent: 40rpx;
			color: rgba(0, 0, 0, 0.35);
			line-height: 2;
			font-size: 28rpx !important;
		}

		/deep/ .u-input__input {
			font-size: 28rpx;
		}
	}

	.codeBox {
		.u-input {
			width: 50%;
		}
	}
</style>